﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System.Linq;

namespace MongoDAO.Builders
{
    public static class DAOQuery<T>
    {
        public static IMongoQuery EQ<TMember, TMemberProperty>(Expression<Func<T, IEnumerable<TMember>>> member, 
            Expression<Func<TMember, TMemberProperty>> memberProperty, TMemberProperty value)
        {
            var memberName = GetMemberName(member);
            var memberPropertyName = GetMemberName(memberProperty);

            var key = String.Format("{0}.{1}", memberName, memberPropertyName);
            var bsonValue = BsonValue.Create(value);

            var queryDocument = new QueryDocument(key, bsonValue);
            return queryDocument;
        }


        public static IMongoQuery In<TMember, TMemberProperty>(Expression<Func<T, IEnumerable<TMember>>> member,
           Expression<Func<TMember, TMemberProperty>> memberProperty, IEnumerable<TMemberProperty> values)
        {
            var memberName = GetMemberName(member);
            var memberPropertyName = GetMemberName(memberProperty);

            var key = String.Format("{0}.{1}", memberName, memberPropertyName);
            var bsonValues = values.Select(value => BsonValue.Create(value));

            var queryDocument = Query.In(key, bsonValues);
            return queryDocument;
        }

      
        //public static IMongoQuery Contains<TMember>(Expression<Func<T, TMember>>  member, TMember value)
        //{
        //    var key = GetMemberName(member);
        //    var stringValue = String.Format("/{0}/", value);
        //    var bsonValue = BsonRegularExpression.Create(value);
        //    var queryDocument = new QueryDocument(key, bsonValue);
        //    return queryDocument;
        //}

        private static string GetMemberName<TEntity, TEntityMember>(Expression<Func<TEntity, TEntityMember>> memberExpression)
        {
            var member = ((MemberExpression)memberExpression.Body).Member as PropertyInfo;
            if (member != null)
                return member.Name;
            throw new ArgumentNullException("memberExpression");
        }

    }
}
